package com.explorati.interview.interview.chapterfifteen.sort;

public class QuickSort {

	public static void sort(Comparable[] arr) {
		int n = arr.length;
		sort(arr, 0, n - 1);
	}

	private static void sort(Comparable[] arr, int l, int r) {
		if (l >= r) {
			return;
		}
		int p = partition(arr, l, r);
		sort(arr, l, p - 1);
		sort(arr, p + 1, r);
	}

	private static int partition(Comparable[] arr, int l, int r) {

		Comparable e = arr[l];

		int j = l;
		for (int i = l + 1; i <= r; i++) {
			if (arr[i].compareTo(e) < 0) {
				j++;
				swap(arr, j, i);
			}
		}
		swap(arr, j, l);
		return j;
	}

	private static void swap(Object[] arr, int a, int b) {
		Object temp = arr[a];
		arr[a] = arr[b];
		arr[b] = temp;
		;
	}
}
